package com.yiwei.zxp.activity;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.RecyclerView;
import android.text.Spanned;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.yiwei.zxp.BussinessMainActivity;
import com.yiwei.zxp.R;
import com.yiwei.zxp.adapter.GoodsDetailAdapter;
import com.yiwei.zxp.api.Api;
import com.yiwei.zxp.api.bean.BuyListBean;
import com.yiwei.zxp.api.bean.FavoriteAddBean;
import com.yiwei.zxp.api.bean.FavoriteDeleteBean;
import com.yiwei.zxp.api.bean.GoodIdBean;
import com.yiwei.zxp.api.bean.ShopAddBean;
import com.yiwei.zxp.api.model.GoodsDetailModel;
import com.yiwei.zxp.base.BaseActivity;
import com.yiwei.zxp.constant.UserInfoGlobal;
import com.yiwei.zxp.event.HomePagerEvent;
import com.yiwei.zxp.event.ShopCartEvent;
import com.yiwei.zxp.util.Dialog;
import com.yiwei.zxp.util.GlideImageLoader;
import com.yiwei.zxp.util.Network;
import com.yiwei.zxp.util.RxLifeUtil;
import com.yiwei.zxp.util.Spans;
import com.yiwei.zxp.util.ToastUtil;
import com.yiwei.zxp.util.UI;
import com.yiwei.zxp.util.Util;
import com.yiwei.zxp.view.BottomIconText;
import com.yiwei.zxp.view.FullyLinearLayoutManager;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class BuyerGoodDetailsActivity extends BaseActivity {


    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.btn_share)
    ImageView btnShare;
    //    @BindView(R.id.pager_goods)
//    ViewPager pagerGoods;
//    @BindView(R.id.indicator)
//    LinePageIndicator indicator;
    @BindView(R.id.txt_goods_title)
    TextView txtGoodsTitle;
    @BindView(R.id.txt_goods_content)
    TextView txtGoodsContent;
    @BindView(R.id.txt_goods_info)
    TextView txtGoodsInfo;
    @BindView(R.id.txt_goods_address)
    TextView txtGoodsAddress;
    @BindView(R.id.txt_goods_type)
    TextView txtGoodsType;
    @BindView(R.id.txt_goods_param)
    TextView txtGoodsParam;
    @BindView(R.id.list_image)
    RecyclerView listImage;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.btn_go_top)
    LinearLayout btnGoTop;
    @BindView(R.id.btn_params)
    LinearLayout btnParams;

    @BindView(R.id.btn_top_cart)
    ImageView btnTopCart;
    @BindView(R.id.btn_shop)
    BottomIconText btnShop;
    @BindView(R.id.btn_collection)
    BottomIconText btnCollection;
    @BindView(R.id.btn_add_cart)
    SuperButton btnAddCart;
    @BindView(R.id.btn_buy_now)
    SuperButton btnBuyNow;
    @BindView(R.id.txt_goods_sell)
    TextView txtGoodsSell;
    @BindView(R.id.index_banner)
    Banner banner;
    private Unbinder unbiner;
    private GoodsDetailAdapter bottomAdapter;
    private int x24;
    private GoodsDetailModel.DatasBean totalData;
    private boolean isCollection = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buyer_goods_detail);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
    }

    private void init() {
        banner.setImageLoader(new GlideImageLoader());
        banner.setIndicatorGravity(BannerConfig.CENTER);
        x24 = getResources().getDimensionPixelSize(R.dimen.x24);
        String good_id = getIntent().getStringExtra("goods_id");
        String goods_no = getIntent().getStringExtra("goods_no");
        bottomAdapter = new GoodsDetailAdapter(this);
        FullyLinearLayoutManager mLayoutManager = new FullyLinearLayoutManager(this);
        listImage.setLayoutManager(mLayoutManager);
        listImage.setNestedScrollingEnabled(false);
        listImage.setAdapter(bottomAdapter);
        getGoodsDetail(good_id, goods_no);


    }

    public void getGoodsDetail(String goods_id, String goods_no) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        GoodIdBean bean = new GoodIdBean();
        bean.goods_id = goods_id;
        bean.goods_no = goods_no;
        Api.api_service.getGoodsDetail(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    totalData = result.datas;
                    setGoodsData(result.datas);
                });
    }


    private void setGoodsData(GoodsDetailModel.DatasBean item) {
//        list = new ArrayList<>();
//        for (int i = 0; i < item.photos.size(); i++) {
//            ImageView imageView = new ImageView(this);
//            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
//            Glide.with(this).load(item.photos.get(i)).into(imageView);
//            list.add(imageView);
//        }
//        adapter = new ImagePagerAdapter(list);
//        pagerGoods.setAdapter(adapter);
//        indicator.setViewPager(pagerGoods);

        banner.setImages(item.photos).start();

        Spanned txt_money = Spans.with(this).
                font("￥", x24, 0xffFF0030).style(Typeface.BOLD).
                font(item.price, getResources().getDimensionPixelSize(R.dimen.x48), 0xffFF0030).style(Typeface.BOLD).
                build();
        txtGoodsTitle.setText(txt_money);

        txtGoodsContent.setText(item.title);

        String fee = "";
        if (Float.valueOf(item.deliver_fee) == 0) {
            fee = "免运费";
            txtGoodsInfo.setTextColor(0xff999999);
        } else {
            fee = item.deliver_fee;
            txtGoodsInfo.setTextColor(0xffFF0030);
        }
        txtGoodsSell.setText("月销：" + item.sell + "笔");
        txtGoodsInfo.setText("快递：" + fee);
        txtGoodsAddress.setText(item.province + item.city);

        txtGoodsType.setText(item.cate_name);
        if (item.params != null && item.params.size() >= 0) {
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < item.params.size(); i++) {
                builder.append(item.params.get(i).name);
                builder.append("、");
            }
            txtGoodsParam.setText(builder.substring(0, builder.length() - 1));
        }

        bottomAdapter.update(item.details);

//        是否收藏
        if (item.is_favorites.equals("1")) {
            isCollection = true;
            btnCollection.setTextColor(0xffFF0030);
            btnCollection.setDrawable(R.mipmap.img_detail_collcetion);
        } else {
            isCollection = false;
            btnCollection.setTextColor(0xff5D5F6A);
            btnCollection.setDrawable(R.mipmap.img_detail_uncollection);
        }
    }


    public void scrollToPosition(int x, int y) {

        ObjectAnimator xTranslate = ObjectAnimator.ofInt(scrollView, "scrollX", x);
        ObjectAnimator yTranslate = ObjectAnimator.ofInt(scrollView, "scrollY", y);

        AnimatorSet animators = new AnimatorSet();
        animators.setDuration(1000L);
        animators.playTogether(xTranslate, yTranslate);
        animators.start();
    }

    public void getCartAdd() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        ShopAddBean bean = new ShopAddBean();
        bean.shop_id = totalData.shop_id;
        bean.goods_id = totalData.goods_id;
        bean.goods_no = totalData.goods_no;
        Api.api_service.getShopAdd(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    EventBus.getDefault().post(new ShopCartEvent());
                    ToastUtil.makeCartTips("加入购物车成功");
                });
    }

    public void getFavoriteAdd(List<FavoriteAddBean> item) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();

        Api.api_service.getFavoriteAdd(item).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    isCollection = true;
                    ToastUtil.makeText(this, "收藏成功");
                    btnCollection.setTextColor(0xffFF0030);
                    btnCollection.setDrawable(R.mipmap.img_detail_collcetion);
                });
    }

    public void getFavoriteDelete(String goods_id) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        FavoriteDeleteBean bean = new FavoriteDeleteBean();
        bean.goods_id = goods_id;
        Api.api_service.getFavoriteDelete(bean).compose(RxLifeUtil.loginCheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    isCollection = false;
                    ToastUtil.makeText(this, "取消收藏");
                    btnCollection.setTextColor(0xff5D5F6A);
                    btnCollection.setDrawable(R.mipmap.img_detail_uncollection);
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbiner.unbind();
        unbiner = null;
    }

    @Override
    public void onStart() {
        super.onStart();
        banner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        banner.stopAutoPlay();
    }

    @OnClick({R.id.btn_check_all, R.id.btn_back, R.id.btn_share, R.id.btn_go_top})
    public void onViewClicked(View view) {
        if (UI.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.btn_check_all:
                Dialog.showGoodsParams(this, totalData.params);
                break;
            case R.id.btn_back:
                finish();
                break;

            case R.id.btn_share:
                break;
            case R.id.btn_go_top:
                scrollView.post(new Runnable() {
                    @Override
                    public void run() {
                        scrollToPosition(0, 0);
                    }
                });
                break;
        }
    }

    @OnClick({R.id.btn_top_cart, R.id.btn_shop, R.id.btn_collection, R.id.btn_add_cart, R.id.btn_buy_now})
    public void onViewClicked1(View view) {
        if (UI.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.btn_top_cart:
                EventBus.getDefault().post(new HomePagerEvent(2));
                Util.startActivity(this, BussinessMainActivity.class);
                finish();
                break;
            case R.id.btn_shop:
                finish();
                break;
            case R.id.btn_collection:
                if (!UserInfoGlobal.isLogin()) {
                    Util.startActivity(this, LoginNewActivity.class);
                    return;
                }
                if (totalData == null) return;
                if (isCollection) {
                    getFavoriteDelete(totalData.goods_id);
                } else {
                    List<FavoriteAddBean> data = new ArrayList<>();
                    data.add(new FavoriteAddBean(totalData.shop_id, totalData.goods_no, totalData.goods_id));
                    getFavoriteAdd(data);
                }
                break;
            case R.id.btn_add_cart:
                if (!UserInfoGlobal.isLogin()) {
                    Util.startActivity(this, LoginNewActivity.class);
                    return;
                }
                if (totalData != null)
                    getCartAdd();
                break;
            case R.id.btn_buy_now:
                if (!UserInfoGlobal.isLogin()) {
                    Util.startActivity(this, LoginNewActivity.class);
                    return;
                }
                if (totalData != null) {
                    Intent intent = new Intent(this, SureOrderActivity.class);
                    intent.putExtra("data", getBuyList());
                    startActivity(intent);
                    finish();
                }
                break;
        }
    }

    public BuyListBean getBuyList() {
        BuyListBean data = new BuyListBean();
        data.items = new ArrayList<>();

        BuyListBean.ItemsBean bean = new BuyListBean.ItemsBean();
        bean.shop_id = totalData.shop_id;
        bean.goods = new ArrayList<>();
        bean.goods.add(new BuyListBean.ItemsBean.GoodsBean(totalData.goods_no, "1"));
        data.items.add(bean);
        return data;
    }
}
